package com.tianyadu.mmall.browser.controller;

import com.tianyadu.mmall.core.common.ResultResponse;
import com.tianyadu.mmall.core.conf.SecurityConstantsConfig;
import com.tianyadu.mmall.core.properties.MallSecurityProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 浏览器安全认证
 *
 * @author xueyj
 * @date 2019-11-01 13:44
 */
@Slf4j
@RestController
public class BrowserSecurityController {
    /**
     * 获取HttpSessionRequest缓存信息
     */
    private RequestCache requestCache = new HttpSessionRequestCache();
    /**
     * 获取security中请求重定向Strategy
     */
    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
    /**
     * 获取security配置信息
     */
    @Autowired
    private MallSecurityProperties mallSecurityProperties;

    /**
     * 用户授权认证,当需要身份认证时跳转此方法处理
     *
     * @param request  Http请求
     * @param response Http响应
     * @return org.springframework.web.servlet.function.ServerResponse
     * @author xueyj
     * @date 2019/11/1-13:45
     */
    @RequestMapping("/authentication/require")
    @ResponseStatus(code = HttpStatus.UNAUTHORIZED)
    public ResultResponse requireAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //  获取缓存中引发跳转请求信息
        SavedRequest savedRequest = requestCache.getRequest(request, response);
        //  获取以*.html结尾文件
        String suffixHtml = SecurityConstantsConfig.SUFFIX_HTML;
        //  自定义登录页面，若系统无明确指定自定义登录页，则采用默认登录页
        String loginPage = mallSecurityProperties.getBrowser().getLoginPage();
        //  若请求信息不为空，即该请求需要身份认证，则引导用户进行身份认证
        if (savedRequest != null) {
            //  获取引发跳转的请求
            String targetUrl = savedRequest.getRedirectUrl();
            log.info("引发跳转的请求是:【{}】", targetUrl);
            //  若当前请求是以html结尾，则引导用户跳转至登录页
            if (StringUtils.endsWithIgnoreCase(targetUrl, suffixHtml)) {
                redirectStrategy.sendRedirect(request, response, loginPage);
            }
        }
        return ResultResponse.createByErrorMessage("访问的服务需要身份认证，请引导用户到登录页");

    }
}